<template>
    <!-- 付外佣申請 -->
    <div class="write-fdh">
        <!-- 操作結果提示 -->
        <msg v-if="doneShow" class="done-msg" :icon="doneIcon">
            <template slot="buttons">
                <router-link class="success-btn" v-if="doneIcon === 'success'" :to="{ name: 'InitiateApplication'}">
                返回首页
                </router-link>
                <a class="success-btn" v-else @click="closeDoneInfo">返回保密申请</a>
            </template>
            <template slot="description">
                <p class="title">{{doneTitle}}</p>
                <p>{{doneMsg}}</p>
            </template>
        </msg>

        <div class="scroll-box" v-show="!doneShow">
            <!-- 文本域 -->
            <my-write-fdh-info ref="fdh"></my-write-fdh-info>
            <!-- 附件 -->
            <my-annex ref="annex"></my-annex>
            <!-- 抄送人 -->
            <my-make-copy ref="makeCopy" :makeCopyParams="makeCopyParams"></my-make-copy>
        </div>

         <!-- 底部組件 -->
        <my-bottom-submit v-if="!doneShow" @click.native="applySubmit"></my-bottom-submit>
        <!-- 加载中 -->
        <loading class="loading-mask" :show="loadingShow" text="加载中..."></loading>
        <!-- 提示彈窗 -->
        <div v-transfer-dom>
            <confirm v-model="turndownShow"
            class="turndown-confirm" title="提示" confirm-text="确认" :show-cancel-button="false">
                <p>{{turndownText}}</p>
            </confirm>
        </div>
    </div>
</template>

<script>
import MakeCopy from '@/components/ApplyWrite/MakeCopy.vue';
import BottomSubmit from '@/components/Bottom/BottomSubmit.vue';
import MyWriteFdhInfo from '@/components/ApplyWrite/WriteFdhInfo.vue';
import MyAnnex from '@/components/ApplyWrite/Annex.vue';
import { Msg, Loading, Confirm, TransferDom } from 'vux';
import qs from 'qs';
export default {
    data () {
      return {
        defaultMakeCopyStaffNo:'11398',
        doneIcon: '',
        doneTitle: '',
        doneMsg: '',
        doneShow: false,
        loadingShow: false,
        required: ['startDate','payCompany','payMoney','payReason'],    // payBank,payAccount
        turndownShow: false,
        turndownText: '',
        makeCopyParams: [],
      };
    },
    directives: {
      TransferDom
    },
    components: {
      Loading,
      Msg,
      Confirm,
      'my-make-copy': MakeCopy,
      'my-bottom-submit': BottomSubmit,
      'my-write-fdh-info': MyWriteFdhInfo,
      'my-annex': MyAnnex
    },
    async mounted () {
      await this.pageInit();
      if (this.$refs.makeCopy.resultList.length === 0) {
        this.$refs.makeCopy.resultList = this.makeCopyParams;
      }
    },
    watch: {
      $route (to, from) {
        setTimeout(() => {
          this.loadingShow = false;
          this.changeDoneInfo(false);
        }, 500);
        this.pageInit(to, from);
      }
    },
    methods: {
        // 頁面初始化
        pageInit: async function (to, from) {
            let isHomeToThisPage;
            if (to && from) {
                isHomeToThisPage = from.name === 'InitiateApplication' && this.$route.name === 'WriteFDH';
            }
            let isReApplyToThisPage = this.$route.query.applyInfo;
            if (isHomeToThisPage) {
                this.$refs.fdh.payForm.startDate = ''
                this.$refs.fdh.payForm.payCompany= ''  // 收款单位          
                this.$refs.fdh.payForm.payMoney= ''    // 申请支付金额   
                this.$refs.fdh.payForm.payMode = '';   // 付款方式        
                this.$refs.fdh.payForm.payBank = ''  // 开户银行
                this.$refs.fdh.payForm.payAccount = '' // 账号
                this.$refs.fdh.payForm.payReason = ''   // 收款事由
                this.$refs.fdh.changeApplyType = '';

                this.$refs.annex.fileList = [];
                this.makeCopyParams = await this.getDefaultMakeCopy();
            } else if (from && from.name === 'SelectPerson' && this.$route.name === 'WriteFDH') {
            } else if (isReApplyToThisPage && this.$route.name === 'WriteFDH') {
                let params = JSON.parse(isReApplyToThisPage);
                this.makeCopyParams = await this.getDefaultMakeCopy();
                let copiers = params.Copiers.slice(1, params.Copiers.length); // 正式
                // let copiers = params.Copiers; // 测试
                if (copiers.length !== 0) {
                    this.getReApplyMakeCopy(copiers);
                }
                this.$refs.fdh.payForm.startDate = params.Content.StartDate
                this.$refs.fdh.payForm.payCompany= params.Content.PayCompany    // 收款单位          
                this.$refs.fdh.payForm.payMoney= params.Content.PayMoney        // 申请支付金额   
                this.$refs.fdh.payForm.payMode= params.Content.PayMode          // 付款方式      
                this.$refs.fdh.payForm.payBank = params.Content.PayBank         // 开户银行
                this.$refs.fdh.payForm.payAccount = params.Content.PayAccount // 账号
                this.$refs.fdh.payForm.payReason = params.Content.PayReason     // 收款事由
                
                if(this.$refs.fdh.payForm.payMode==='轉賬'||this.$refs.fdh.payForm.payMode==='转账'){
                    this.$refs.fdh.payModeNoCash = true
                    this.$refs.fdh.payModeCash = false
                }else{
                    this.$refs.fdh.payModeNoCash = false
                    this.$refs.fdh.payModeCash = true
                }

                // console.log(b);
                // console.log(b.Content);
                // console.log(b.Content.payCompany);
                // console.log('付外佣表单', this.$refs.fdh.payForm);
                if(params.Content.Files && params.Content.Files.length>0){
                    this.$refs.annex.fileList = params.Content.Files
                }
                if (this.$route.query.titleName === '修改申请') {
                    // this.$refs.askLeaveInfo.reApplyReasonShow = true;
                    this.$refs.fdh.editApplyReason = '';
                    this.required.push('EditApplyReason');
                    this.$refs.fdh.changeApplyType = '修改申请原因'; 
                } else if (params.IsReApply === true) {
                    this.$refs.fdh.reApplyReason = '';
                    this.required.push('ReApplyReason');
                    this.$refs.fdh.changeApplyType = '重新申请原因';
                }
            } else {
                this.makeCopyParams = await this.getDefaultMakeCopy();
            }
        },
        // 提交事件
        applySubmit: function () {
            if (this.loadingShow) {
                return false;
            }
            let ContentData = {
                files: this.$refs.annex.fileList,
                ...this.$refs.fdh.payForm
            };
            if (this.$refs.fdh.changeApplyType === '重新申请原因') {
                ContentData.ReApplyReason = this.$refs.fdh.reApplyReason;
            }
            if (this.$refs.fdh.changeApplyType === '修改申请原因') {
                ContentData.EditApplyReason = this.$refs.fdh.editApplyReason;
            }

            // 转账形式
            
            if(this.$refs.fdh.payModeNoCash){
                ContentData.payMode = '轉賬'
                var index = this.required.indexOf('payBank');
                if (index > -1) {
                    this.required.splice(index, 1);
                }
                index = this.required.indexOf('payAccount');
                if (index > -1) {
                    this.required.splice(index, 1);
                }
                this.required.push('payBank')
                this.required.push('payAccount')
            }else if(this.$refs.fdh.payModeCash) {
                ContentData.payMode = '現金'
                // this.required.remove('payAccount')
                var index = this.required.indexOf('payBank');
                if (index > -1) {
                    this.required.splice(index, 1);
                }
                index = this.required.indexOf('payAccount');
                if (index > -1) {
                    this.required.splice(index, 1);
                }
            }
            // 提交的数据
            let postData = {
                data: {
                    Type: 6,
                    CreatedStaffNo: this.getUserInfo().StaffNo,
                    Copiers: this.parseCopiers(),
                    Content: JSON.stringify(ContentData)
                }
            };
            if(!this.$refs.fdh.payModeCash && !this.$refs.fdh.payModeNoCash){
                this.turndownShow = true;
                this.turndownText = '请选择付款方式';
                return false;
            }

            // console.log(this.required);
            // 判断必填项填写情况
            for (let prop in this.required) {
                let propName = this.required[prop];
                if (ContentData[propName] === '') {
                    this.turndownShow = true;
                    this.turndownText = '请输入必填項';
                    return false;
                }
            }
            if(ContentData.payMode === '轉賬'){
                let bankReg = /^([1-9]{1})(\d{14}|\d{18})$/;    // 银行卡号规则  test('6210812470004250007')); 
                ContentData.payAccount = ContentData.payAccount.trim().replace(/\s+/g, "")
                // console.log(ContentData.payAccount);
                if(!this.authPhone(bankReg,ContentData.payAccount)){
                    this.turndownShow = true;
                    this.turndownText = '请输入正确银行号码'; 
                    return false
                }
            }
   
            // 打印查看传入的数据
            // console.log(postData);
            this.loadingShow = true;
            if (this.$route.query && this.$route.query.titleName === '修改申请') {
                postData.data.KeyId = JSON.parse(this.$route.query.applyInfo).KeyId;
                this.editRequest(postData);
            } else {
                if (this.$route.query.applyInfo !== undefined) {
                    let query = JSON.parse(this.$route.query.applyInfo);
                    if (query.IsReApply !== undefined) {
                        postData.data.IsReApply = query.IsReApply;
                    }
                }
                this.createRequest(postData);
            }
        },
        // 编辑
        editRequest: function (params) {
            this.loadingShow = true;
            this.axios.post('/Process/EditAskForLeaveInfo', qs.stringify(params))
            .then((res) => {
                if (res.data.IsSuccess === true) {
                    this.loadingShow = false;
                    this.changeDoneInfo(true, 'success', '提交修改成功', '你的申请已成功提交修改，等待上级领导审批中');
                } else {
                    this.loadingShow = false;
                    this.changeDoneInfo(true, 'warn', '提交修改失败', `你的申请未能成功提交修改，具体错误：${res.data.ExMessage}`);
                }
            })
            .catch((err) => {
                this.loadingShow = false;
                this.changeDoneInfo(true, 'warn', '提交修改失败', `你的申请未能成功提交修改，具体错误：${err}`);
            });
        },
        // 新增
        createRequest(params){
            this.loadingShow = true;
            this.axios.post('/Process/Create', qs.stringify(params))
            .then((res) => {
                if (res.data.IsSuccess === true) {
                    this.loadingShow = false;
                    this.changeDoneInfo(true, 'success', '提交申请成功', '你的申請已成功提交，等待上级领导审批中');
                } else {
                    this.loadingShow = false;
                    this.changeDoneInfo(true, 'warn', '提交申请失败', `你的申请未能成功提交，具体错误：${res.data.ExMessage}`);
                }
            })
            .catch((err) => {
                this.loadingShow = false;
                this.changeDoneInfo(true, 'warn', '提交申请失败', `你的申请未能成功提交，具体错误：${err}`);
            });
        },
        // 根据正则，判断内容是否符合规则
        authPhone(reg,mobile) {
        // /^[1][3-8]\d{9}$|^([6|9])\d{7}$|^[0][9]\d{8}$|^[6]([8|6])\d{5}$/
            if (!(reg.test(mobile))) {
                return false
            }else {
                return true
            }
        },
        changeDoneInfo: function (status, iconType, title, msg) {
            this.doneIcon = iconType;
            this.doneTitle = title;
            this.doneMsg = msg;
            this.doneShow = status;
        },
        closeDoneInfo: function () {
            this.changeDoneInfo(false, '', '', '');
        },
        // 抄送人格式轉換 （只POST StaffNo）
        parseCopiers: function () {
            let copiers = this.$refs.makeCopy.resultList;
            let newCopiers = [];
            copiers.forEach((item) => {
            newCopiers.push({StaffNo: item.userid});
            });
            return newCopiers;
        },
        getDefaultMakeCopy: async function () {
            let postData = {
                data: {
                    StaffNoArr:[{StaffNo:this.defaultMakeCopyStaffNo}]
                }
            };
            this.loadingShow = true;
            try {
                let res = await this.axios.post('/Wechat/QueryUsersFromStaffNo', qs.stringify(postData))
                this.loadingShow = false;
                if (res.data.IsSuccess === true) {
                    res.data.data.Users[0]["checked"] = true;
                    res.data.data.Users[0]["removeSwitch"] = false;
                    let makeCopyArr = res.data.data.Users;
                    return makeCopyArr;
                } else {
                    this.turndownShow = true;
                    this.turndownText = '获取默认抄送人失败';
                    return [];
                }
            } catch(err){
                this.loadingShow = false;
                this.turndownShow = true;
                this.turndownText = '获取默认抄送人失败';
                console.log(err)
            }
        },
        getReApplyMakeCopy: function (staffNoArr) {
            let postData = {
                data: {
                    StaffNoArr: staffNoArr
                }
            };
            this.loadingShow = true;
            return this.axios.post('/Wechat/QueryUsersFromStaffNo', qs.stringify(postData))
            .then((res) => {
                this.loadingShow = false;
                if (res.data.IsSuccess === true) {
                    this.makeCopyParams = this.makeCopyParams.concat(res.data.data.Users);
                    this.$refs.makeCopy.resultList = this.makeCopyParams;
                } else {
                    this.turndownShow = true;
                    this.turndownText = '获取抄送人失败';
                }
            })
            .catch(() => {
                this.loadingShow = false;
                this.turndownShow = true;
                this.turndownText = '获取抄送人失败';
            });
        }
    },
}
</script>

<style lang="scss" scoped>
    @import '../../assets/style/variable';
    .write-fdh{
        -webkit-overflow-scrolling: touch;
    }
</style>